package com.welsy.usermgt.command
{
	import com.adobe.cairngorm.commands.Command;
	import com.adobe.cairngorm.model.ModelLocator;
	import com.adobe.cairngorm.control.CairngormEvent;
	import flash.events.Event;
	import com.welsy.usermgt.business.SearchDelegate;
	import com.welsy.usermgt.event.SearchEvent;
	import com.welsy.usermgt.model.UserMgtModelLocator;
	import mx.controls.Alert;
	import com.welsy.usermgt.vo.SearchVO;
	import com.welsy.usermgt.vo.UsrResultVO;
	import mx.collections.ArrayCollection;
	import com.welsy.usermgt.vo.UserVO;
	import mx.rpc.IResponder;
	import com.welsy.util.NamespaceLocator;	
	
	public class SearchCommand implements Command, IResponder
	{
		private var model : UserMgtModelLocator = UserMgtModelLocator.getInstance();
		
		public function execute(event : CairngormEvent):void {
			var delegate : SearchDelegate = new SearchDelegate(this);
			var searchEvent : SearchEvent = SearchEvent(event);
			delegate.getServerSrcResult(searchEvent.searchVO);
		}
		
		public function result( event : Object) :void {
			//we are expecting a XMLList
			var xusers : XMLList = XMLList(event.result);
			var pusers : ArrayCollection = new ArrayCollection;
			
			//Let's parse it
			var NS : Namespace = new Namespace(NamespaceLocator.USER_MGT_DATATYPES);
			
			var TAG_USERCOLL : QName = new QName(NS, "UsersCollection");
			
			var TAG_FIRSTNAME : QName = new QName(NS, "FirstName");
			var TAG_LASTNAME : QName = new QName(NS, "LastName");
			var TAG_LOGIN : QName = new QName(NS, "Login");
			var TAG_EMAIL : QName = new QName(NS, "Email");
			var TAG_SUBSYSTMID : QName = new QName(NS, "SubSystemId");
			var TAG_USERID : QName = new QName(NS, "UserId");
			var TAG_ROLEID : QName = new QName(NS, "RoleId");			
			
			var list:XMLList =  xusers.descendants(TAG_USERCOLL).children();
			
			for each(var xnod : XML in list) {
				
				var uvo : UserVO = new UserVO;
				
				uvo.FirstName = xnod.child(TAG_FIRSTNAME);
				uvo.LastName = xnod.child(TAG_LASTNAME);
				uvo.Login = xnod.child(TAG_LOGIN);
				uvo.Email = xnod.child(TAG_EMAIL);
				uvo.UserId = xnod.child(TAG_USERID);
				uvo.SubSystemId = xnod.child(TAG_SUBSYSTMID);
				uvo.RoleId = xnod.child(TAG_ROLEID);
								
				pusers.addItem(uvo);
			}
			
			//Update the model
			var result : UsrResultVO = new UsrResultVO(pusers);
			model.result = result;
			
		}
		
		public function fault( event : Object ):void {
			//TODO: report the error
			Alert.show("usermgt.command.SearchCommand.fault!");
		}
	}
}